package utils

import (
	"fmt"
	"time"
)

type counter struct {
	begin time.Time
	end   time.Time
	diff  float64
}

type TimeCounter map[string]counter

// 创建计时器容器
func NewTimeCounter() TimeCounter {
	return TimeCounter{}
}

// 开始一个计时器
func (tc TimeCounter) Begin(flag string) {
	tc[flag] = counter{
		begin: time.Now(),
	}
}

// 结束一个计时器
func (tc TimeCounter) End(flag string) float64 {
	c, ok := tc[flag]
	if !ok {
		_ = fmt.Errorf("标记 %s 计时器尚未开始", flag)
		return 0
	}
	c.end = time.Now()
	c.diff = float64((c.end.UnixMicro() - c.begin.UnixMicro())) / 1000000
	tc[flag] = c
	return c.diff
}

// 信息输出
func (tc TimeCounter) String() (str string) {
	for flag, c := range tc {
		str += fmt.Sprintf("Flag: %s, begin: %s; end: %s, diff:%f\n", flag, c.begin, c.end, c.diff)
	}
	return
}
